package mspbots.teams.data.core.planners;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.teams.common.ResultMsg;
import mspbots.teams.data.core.BaseReceiver;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Jay Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class TasksReceiver extends BaseReceiver {

    private final TasksRepository tasksRepository;

    @RabbitListener(queues = "data-teams.planners-tasks.sync")
    public void processCompanies(ResultMsg resultMsg) {
        Tasks data = Tasks.builder().otherId(resultMsg.getId()).build();
        data.setExtend(resultMsg.getEntity());
        data.setTenantId(resultMsg.getTenantId());
        data.setGroupId(resultMsg.getEntity().get("plans").get("owner").textValue());
        data.setPlanId(resultMsg.getEntity().get("planId").textValue());
        data.setCreateTime(LocalDateTime.parse(resultMsg.getEntity().get("createdDateTime").textValue(),
                DateTimeFormatter.ISO_DATE_TIME));

        String duDateTimeStr = resultMsg.getEntity().get("dueDateTime")
                .asText(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));

        data.setUpdateTime(LocalDateTime.parse(duDateTimeStr, DateTimeFormatter.ISO_DATE_TIME));


        data.setSyncTime(resultMsg.getSyncDate());

        this.tasksRepository.findByIds(data.getTenantId(), data.getGroupId(), data.getPlanId(), data.getOtherId())
                .switchIfEmpty(this.tasksRepository.save(data))
                .filter(old -> old.getUpdateTime().isBefore(data.getUpdateTime()))
                .map(resultNode -> {
                    data.setId(resultNode.getId());
                    return data;
                })
                .flatMap(this.tasksRepository::save).block(Duration.ofSeconds(10));
    }
}
